﻿using EnvDTE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace Axiom.CodeManifold
{
	public class AddMethodRequest
	{
		public AddMethodRequest()
		{
			SelectedRepository = CodePropertyEx.Empty;
		}

		public bool AddTests { get; set; }

		public string AggregateName
		{
			get
			{
				string serviceName = string.Empty;

				string pattern = "I(.*)Service";
				Match m = Regex.Match(ServiceName, pattern);
				if (m.Success)
				{
					serviceName = m.Groups[1].ToString();
				}

				return serviceName;
			}
		}

		public string GatewayInterfaceName { get { return "I" + AggregateName + "Gateway"; } }

		public string GatewayName { get { return AggregateName + "Gateway"; } }

		public MethodDefinition Method { get; set; }

		public string Namespace { get; set; }

		public string ProxyName { get { return AggregateName + "ServiceClient"; } }

		public CodePropertyEx SelectedRepository { get; set; }

		public string ServiceImplementationName { get { return AggregateName + "Service"; } }

		public string ServiceName { get; set; }

		public string Signature
		{
			get
			{
				StringBuilder sb = new StringBuilder();
				List<string> arguments = new List<string>();

				var name = Method.Name;
				var type = Method.ReturnType;

				sb.AppendFormat(@"{0} {1}.{2}(", Namespace, type, name);

				foreach (Parameter parameter in Method.Parameters)
				{
					var parametername = parameter.Name;
					var parametertype = parameter.Type;
					arguments.Add(string.Format(@"{0}  {1}", parametertype, parametername));
				}
				sb.Append(string.Join(",", arguments.ToArray()));
				sb.Append(")");

				return sb.ToString();
			}
		}

		public bool Success { get; set; }
	}

	public class CodePropertyEx
	{

		private static CodePropertyEx _empty = new CodePropertyEx()
		{
			InterfaceName = EmptyName,
			PropertyName = EmptyName,
			ImplementationClass = EmptyName,
		};

		private static string EmptyName = "-None-";

		public static CodePropertyEx Empty
		{
			get
			{
				return _empty;
			}
		}

		public string FriendlyName
		{
			get
			{
				string result = null;
				Regex regex = new Regex(@"(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])", RegexOptions.Compiled);
				if (string.IsNullOrWhiteSpace(ImplementationClass))
				{
					return string.Empty;
				}

				result = regex.Replace(ImplementationClass, " $1").Trim();

				return result;
			}
		}

		public string ImplementationClass { get; set; }

		public string InterfaceName { get; set; }

		public bool IsEmpty
		{
			get
			{
				return PropertyName.CompareTo(EmptyName) == 0;
			}
		}

		public string PropertyName { get; set; }

		public override string ToString()
		{
			return FriendlyName;
		}
	}
}
